package com.gagakuai.engine.impl.pvm.runtime;

import com.gagakuai.engine.delegate.ExecutionListener;
import com.gagakuai.engine.impl.pvm.process.ScopeImpl;
import com.gagakuai.engine.impl.runtime.InterpretableExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/*
 * @program: common-starters
 * @description: 抽象事件原子操作类
 * @author: houhong
 * @create: 2023-01-02 19:17
 */
public abstract class AbstractEventAtomicOperation implements AtomicOperation {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    /*
     * @param execution
     * @return
     * @Author houhong
     * @Description //TODO 作为所有的原子类的执行模版方法使用
     *                     主要工作是执行监听器
     * @Date 3:18 下午 2023/4/30
     */
    @Override
    public void execute(InterpretableExecution execution) {

        //// TODO: 2023/1/2  先执行： 执行监听器
        ScopeImpl scope = getScope(execution);
        //根据事件名字： start/end/take 获取对应的监听器
        List<ExecutionListener> executionListeners = scope.getExecutionListeners(getEventName());

        Integer executionListenerIndex = execution.getExecutionListenerIndex();

        if(executionListeners.size() > executionListenerIndex){
            execution.setEventName(getEventName());
            execution.setEventSource(scope);
            //可以执行监听器
            if(execution.shouldExecuteListeners()){
                ExecutionListener listener = executionListeners.get(executionListenerIndex);
                try {
                    listener.notify(execution);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //next
                execution.setExecutionListenerIndex(executionListenerIndex+1);
                execution.performOperation(this);
            }

        }else{
            execution.setExecutionListenerIndex(0);
            execution.setEventName(null);
            execution.setEventSource(null);
            //监听器执行完毕后执行 当前原子类的业务，子类实现自己的业务
            eventNotificationsCompleted(execution);
        }
    }

    /*
     * 默认是false
     */
    @Override
    public Boolean isAsync(InterpretableExecution execution) {

        return Boolean.FALSE;
    }

    /*
     * 事件名
     */
    protected abstract String getEventName();

    protected abstract ScopeImpl getScope(InterpretableExecution execution);

    /*
     * 事件通知完成
     */
    protected abstract void eventNotificationsCompleted(InterpretableExecution execution);
}